package com.wilson.treeviewer.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserUtil {

    public static List<UserNode> createNodes(List<User> users) {
        Map<String, UserNode> nodeMap = new HashMap<>();
        for (User user : users) {
            nodeMap.put(user.getId(), new UserNode(user));
        }

        for (User user : users) {
            UserNode node = nodeMap.get(user.getId());
            UserNode parentNode = nodeMap.get(user.getManagerId());

            if (parentNode != null) {
                node.setParentNode(parentNode);
                parentNode.addChild(node);
            }
        }

        List<UserNode> nodes = new ArrayList<>();
        nodes.addAll(nodeMap.values());

        return nodes;
    }

    public static UserTree createTree(List<User> users) {
        List<UserNode> nodes = createNodes(users);
        UserTree tree = new UserTree(nodes);
        return tree;
    }
}
